<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\shop_admin\service;


use app\shop_admin\model\SystemLog;
use think\Paginator;

class JournalService
{
    /**
     * @param array $data
     * @return array
     */
    public function readLog(array $data)
    {
        $res = SystemLog::where($this->bulidWhere($data))
            ->alias('a')
            ->join('admin d', 'a.admin_id=d.id', 'LEFT')
            ->field('a.ip,a.content,a.operation_type,a.create_time,d.username')
            ->paginate(['page' => $data['page'], 'list_rows' => $data['size']]);
        return [HTTP_SUCCESS,$res];
    }

    private function bulidWhere(array $data)
    {
        $where = [];
        $arr = [];
        $res = [];
        !empty($data['name']) && $where[] = ['d.username', 'like', "%" . $data['name'] . "%"];
        if (array_key_exists('start_time', $data) && array_key_exists('end_time', $data))
            $arr = $this->setTime($data['start_time'], $data['end_time']);
        return array_merge($where, $arr, $res);
    }

    private function setTime($start_time, $end_time)
    {
        $arr = [];
        if (!empty($start_time) && !empty($end_time))
            $arr[] = ['a.create_time', 'between', [$start_time, $end_time]];
        elseif (!empty($start_time) && empty($end_time))
            $arr[] = ['a.create_time', 'between', [$start_time, date('Y-m-d H:i:s', time())]];
        elseif (empty($start_time) && !empty($end_time))
            $arr[] = ['a.create_time', 'between', [date('Y-m-d H:i:s', strtotime($end_time) - 60), $end_time]];
        return $arr;
    }
}